<?php
class ControllerArticleCategory extends AdminController {

	protected static $MODULE_ARTICLE = 1;
	protected static $MODULE_HELP = 2;
	
	public function index() {
		M('article/article', 'article_mod');
		$this->getList();
	}

	public function insert() {
		M('article/article', 'article_mod');
		if ($this->request->isPost()) {
			$this->article_mod->addCategory($this->request->post);

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('article/category'));
		}
		$this->getForm();
	}

	public function update() {
		M('article/article', 'article_mod');
		if ($this->request->isPost()) {
			$this->article_mod->editCategory($this->request->get['category_id'], $this->request->post);
				
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('article/category'));
		}
		$this->getForm();
	}

	public function delete() {
		M('article/article', 'article_mod');
		if ($this->request->post['selected'] && $this->validateDelete()) {
			$this->article_mod->deleteCategory($this->request->post['selected']);
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('article/category'));
		}
		$this->getList();
	}

	protected function getList() {
		$this->document->setTitle($this->_['heading_title']);
		$this->data['categories'] = $this->article_mod->getCategories();
		
		$this->display('article/category_list.tpl');
	}

	protected function getForm() {
		$this->document->addScript(ROOT . 'static/javascript/jquery/jquery.validate.js');
		$this->document->setTitle($this->_['heading_title']);
		$category_id = G('category_id');
		if ($category_id) {
			$this->data['action'] = UA('article/category/update', "category_id=$category_id");
			if (!$this->request->isPost()) {
				$this->vo->data = $this->article_mod->getCategory($category_id);
			}
		}
		else {
			$this->data['action'] = UA('article/category/insert');
		}
		$this->display('article/category_form.tpl');
	}

	protected function validateDelete() {
		foreach ($this->request->post['selected'] as $category_id) {
			$total = $this->article_mod->getTotalArticlesByCategoryId($category_id);
			if ($total > 0) {
				$this->setMessage('error_warning', sprintf($this->_['error_warning'], $total));
				return false;
			}
		}
		return true;
	}
}